package cn.net.xyan.text.app


import cn.net.xyan.text.listener.MouseListener
import cn.net.xyan.text.view.MainView
import org.jnativehook.GlobalScreen
import org.jnativehook.NativeHookException
import tornadofx.App
import java.util.logging.Logger
import java.util.logging.ConsoleHandler
import java.util.logging.Level
import javafx.stage.Stage
import java.io.PrintWriter
import java.io.StringWriter
import java.util.*
import java.util.logging.Formatter;
import java.util.logging.LogRecord




class MyApp: App(MainView::class, Styles::class){

    private val logger = Logger.getLogger(GlobalScreen::class.java.`package`.name)

    private inner class LogFormatter : Formatter() {
        override fun format(record: LogRecord): String {
            val line = StringBuilder()

            line.append(Date(record.millis))
                    .append(" ")
                    .append(record.level.localizedName)
                    .append(":\t")
                    .append(formatMessage(record))

            if (record.thrown != null) {
                try {
                    val sw = StringWriter()
                    val pw = PrintWriter(sw)
                    record.thrown.printStackTrace(pw)
                    pw.close()
                    line.append(sw.toString())
                    sw.close()
                } catch (ex: Exception) { /* Do Nothing */
                }

            }

            return line.toString()
        }
    }

    init {

        // Disable parent logger and set the desired level.
        logger.useParentHandlers = false
        logger.level = Level.ALL

        // Add our custom formatter to a console handler.
        val handler = ConsoleHandler()
        handler.formatter = LogFormatter()
        handler.level = Level.WARNING
        logger.addHandler(handler)

//        Runtime.getRuntime().addShutdownHook(Thread(Runnable {
//            GlobalScreen.unregisterNativeHook()
//        }))
    }

    override fun start(stage: Stage) {
        super.start(stage)

        try {
            GlobalScreen.registerNativeHook()
        } catch (ex: NativeHookException) {
            System.err.println("There was a problem registering the native hook.")
            System.err.println(ex.message)

            System.exit(1)
        }

        val listener = MouseListener()



        GlobalScreen.addNativeMouseListener(listener)
    }

    override fun stop() {

        GlobalScreen.unregisterNativeHook()

        super.stop()
    }


}